import cloud from '@lafjs/cloud'
import { stat } from 'node:fs'
let dbName = "admin-class-student"
const db = cloud.mongo.db
let data

export default async function (ctx: FunctionContext) {
  data = ctx.body.data

  switch (ctx.body.type) {
    case "notPassed":
      return await notPassedList()
      break;

    default: //历史学员
      return await list()
      break;
  }
}

async function notPassedList() {
  let whereJson = { ...data }
  delete whereJson.pageIndex
  delete whereJson.pageSize
  delete whereJson.type
  delete whereJson.affiliation
  whereJson = cloud.utils.fuzzyQuery({ ...whereJson })

  let userIds = []
  let params = ["name", "mobile", "identityCard", 'enterprise', "workYears", "education", "graduationMajor"]
  let query = {}
  params.forEach(element => {
    if (whereJson.hasOwnProperty(element)) {
      query[`baseInfo.${element}`] = whereJson[element]
    }
  });

  //报名所属
  if (data.affiliation && data.affiliation.length) {
    query["baseInfo.affiliation"] = { $in: data.affiliation }
  }

  if (!cloud.utils.isEmptyObject(query)) {
    let users = await db.collection("web-users").find(query).project({ _id: 1 }).toArray()
    users.forEach(element => { userIds.push(element._id) });
  }


  //查询已结业的班级
  let accordWithClass = await db.collection("admin-class").find({ status: { $in: [2] } }).project({ _id: 1 }).toArray()
  let classIds = []
  accordWithClass.forEach(element => { classIds.push(element._id) });

  //最后入参
  let obj = {
    classId: { $in: classIds },
    isExamination: { $in: [0, 2] },//缺考的
  }
  if (userIds.length) obj['userId'] = { $in: userIds }

  let res = await cloud.nw.db.selects({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    // 主表 where 条件
    whereJson: obj,
    // 主表排序规则
    sortArr: [
      { "name": "graduationTime", "type": "desc" },
      { "name": "userPinyin", 'type': "asc" },
    ],
    // 副表列表
    foreignDB: [
      {
        dbName: "admin-class",//副表 order
        localKey: "classId",
        foreignKey: "_id",
        as: "class_Info",
        limit: 1,
        // 副表字段显示规则
        fieldJson: {
          className: 1
        },
      },
      {
        dbName: "web-users",//副表 order
        localKey: "userId",
        foreignKey: "_id",
        as: "user_Info",
        limit: 1,
        // 副表字段显示规则
        fieldJson: {
          baseInfo: 1
        },
      },
      {
        dbName: "admin-class-signIn",//签到记录
        localKey: "classId",
        foreignKey: "classId",
        as: "signIn_data",
        limit: 10000,
        fieldJson: { status: 1, userId: 1 },
      },
      {
        dbName: "admin-teaching-schedule",//班级排期
        localKey: "classId",
        foreignKey: "classId",
        as: "schedule_data",
        limit: 100,
        fieldJson: { _id: 1 },
      },
      {
        dbName: "admin-class-report-B3-list",//B3学生地址
        localKey: "classId",
        foreignKey: "classId",
        as: "B3_data",
        limit: 100,
        fieldJson: { userId: 1, address: 1 },
      },
      {
        dbName: "admin-class-offline-student",//线下学员
        localKey: "offlineUserId",
        foreignKey: "_id",
        as: "user_data",
        limit: 1,
      },
    ]
  });
  return cloud.utils.requestReturn({ data: res })
}

//学员列表
async function list() {
  let whereJson = { ...data }
  delete whereJson.pageIndex
  delete whereJson.pageSize
  delete whereJson.type
  delete whereJson.affiliation
  delete whereJson.needSourceFile //是否需要查团队导入学员
  delete whereJson.isExamination //是否筛选获证情况

  whereJson = cloud.utils.fuzzyQuery({ ...whereJson })

  let orderIds = []
  let params = ["name", "mobile", "identityCard", 'enterprise', "workYears", "education", "graduationMajor"]
  let query = {}
  params.forEach(element => {
    if (whereJson.hasOwnProperty(element)) {
      query[`approvalContent.model.${element}`] = whereJson[element]
    }
  });

  //报名所属
  if (data.affiliation && data.affiliation.length) {
    query["approvalContent.model.affiliation"] = { $in: data.affiliation }
  }

  if (!cloud.utils.isEmptyObject(query)) {
    //符合要求的订单
    let users = await db.collection("web-order").find(query).project({ _id: 1 }).toArray()
    users.forEach(element => { orderIds.push(element._id) });
  }

  //拿到班级ID
  let aa = []
  //符合要求的班级
  let accordWithClass = []
  //班级查找入参
  let classParams = {}

  // if (data.type == 'current') { //查询在读学员
  //   classParams["status"] = { $in: [0, 1] }
  // } else if (data.type == 'history') { //历史学员
  //   classParams["status"] = { $in: [2] }
  // }
  accordWithClass = await db.collection("admin-class").find(classParams).project({ _id: 1 }).toArray()
  accordWithClass.forEach(element => { aa.push(element._id) });
  if (data.classId && data.classId.length) {
    aa = cloud.utils.getCommonElements2(aa, data.classId)
  }

  //最后入参
  let obj = { classId: { $in: aa } }

  //如果是查团体学员，则查导入学员
  if (data.type == 'offline') {
    obj['source'] = { $exists: true }
    delete obj['classId']
  }

  //needSourceFile：是否需要查线下导入学员
  if (data.needSourceFile && (data.needSourceFile == 0)) obj['source'] = { $exists: false }
  if (data.isExamination && data.isExamination.length) obj['isExamination'] = { $in: data.isExamination }

  //筛选订单成员
  if (!cloud.utils.isEmptyObject(query)) {
    let bb = await db.collection(dbName).find({ classId: { $in: aa } }).project({ orderId: 1 }).toArray()
    let list = []
    bb.forEach(element => { list.push(element.orderId) });
    obj['orderId'] = { $in: cloud.utils.getCommonElements2(orderIds, list) }
  }

  let res = await cloud.nw.db.selects({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    // 主表 where 条件
    whereJson: obj,
    // 主表排序规则
    sortArr: [
      { "name": "classId", "type": "desc" },
      { "name": "userPinyin", 'type': "asc" },
    ],
    // 副表列表
    foreignDB: [
      {
        dbName: "admin-class",//副表 order
        localKey: "classId",
        foreignKey: "_id",
        as: "class_Info",
        limit: 1,
        // 副表字段显示规则
        fieldJson: {
          className: 1,
          status: 1
        },
      },
      {
        dbName: "web-users",//副表 order
        localKey: "userId",
        foreignKey: "_id",
        as: "user_Info",
        limit: 1,
        // 副表字段显示规则
        fieldJson: {
          baseInfo: 1
        },
      },
      {
        dbName: "web-order",//副表 order
        localKey: "orderId",
        foreignKey: "_id",
        as: "order_Info",
        limit: 1,
        // 副表字段显示规则
        fieldJson: { orderUserInfo: 1 },
      },
      {
        dbName: "admin-class-signIn",//签到记录
        localKey: "classId",
        foreignKey: "classId",
        as: "signIn_data",
        limit: 10000,
        fieldJson: { status: 1, userId: 1 },
      },
      {
        dbName: "admin-teaching-schedule",//班级排期
        localKey: "classId",
        foreignKey: "classId",
        as: "schedule_data",
        limit: 100,
        fieldJson: { _id: 1 },
      },
      {
        dbName: "admin-class-report-B3-list",//B3学生地址
        localKey: "classId",
        foreignKey: "classId",
        as: "B3_data",
        limit: 100,
        fieldJson: { userId: 1, address: 1 },
      },
      {
        dbName: "admin-class-offline-student",//线下学员
        localKey: "offlineUserId",
        foreignKey: "_id",
        as: "user_data",
        limit: 1,
      },
    ]
  });
  return cloud.utils.requestReturn({ data: res })
}